(function(window, css_url, undefined) {
'use strict';

// #[function("createLink", "添加link")]
// #[param("url", "css地址")]
function createLink(url) {
    if (!url) return;

    var link = document.createElement("link");
    link.setAttribute("rel", "stylesheet");
    link.setAttribute("type", "text/css");
    link.setAttribute("href", url);

    var heads = document.head || document.getElementsByTagName('head')[0];

    heads.appendChild(link);
}

// #[function("createElem", "创建元素")]
// #[param1("elemName", "创建元素节点的名称")]
// #[param2("appendElem", "追加在那个元素里面")]
// #[return("返回创建的元素节点")]
function createElem(elemName, appendElem) {
    if (!elemName) return;

    var elem = document.createElement(elemName); // 创建元素节点
    if (appendElem) {
        appendElem.appendChild(elem);
    }else{
        document.body.appendChild(elem);
    }

    return elem;
}

// #[function("removeElem", "删除元素节点")]
// #[param1("elemName", "删除元素节点名称")]
function removeElem(elemName) {
    if (!elemName) return;
    elemName.remove();
}

// #[function("setStyle", "设置 元素 的 style")]
// #[param1("elem", "给那个元素添加样式")]
// #[param1("style", "样式表")]
function setStyle(elem, style = {}) {
    if (!elem) return;

    for (var val in style) {
        elem.style[val] = style[val];
    }
}

// #[function("getStyle", "获取元素的属性值 getComputedStyle",
//     "getComputedStyle 的第二个参数 是获取伪元素的样式表")]
// #[param1("obj elem", "元素")]
// #[param2("str prop", "样式属性名 eg: width")]
// #[return("返回属性值")]
function getStyle(elem, prop) {
    if (window.getComputedStyle) {
        return window.getComputedStyle(elem, null)[prop];
    }else{
        return elem.currentStyle[prop];
    }
}

// 加载 css
(function() {
    if (!css_url) {
        return console.log('css url not null');
    }
    createLink(css_url);
}());

    var Layer = function(config) {
        var that = this;

        // 客户端
        that.ifmob = /Android|webOS|iPhone|iPad|BlackBerry/i.test(navigator.userAgent);

        // 主id
        var rand = Math.random().toString().split('.')[1];
        var mainid = 'layer_'+rand;
        that.mainid = mainid;

        // 回调函数
        if (config.callback) {
            if (typeof(config.callback) === "function") {
                that.callback = config.callback;
            }
        }

        // config
        var config = that.namefix(config);
        that.config = config;
        var xcstr = '';
        if (typeof(config.reset) !== "undefined" &&
            config.reset !== null &&
            config.reset === false){
            for (var key in config) {
                if(config[key] !== null){
                    xcstr += config[key].toString();
                }
            }
            that.xcstr = that.xcstrRep(xcstr);
        }else{
            that.xcstr = xcstr;
        }

        // 关闭
        if (config.model === 'close') {
            that.close(config.closeid);
            return false;
        }

        // 关闭所有
        if (config.model === 'closeAll') {
            that.closeAll();
            return false;
        }

        //入口
        that.creat();
    };

    Layer.parent = Layer.prototype;

    // 参数名称补全
    Layer.parent.namefix = function(config) {
        // 方位
        if (config.position) {
            config.position = config.position.toLowerCase();
            if (config.position === 't') {
                config.position = 'top';
            }else if (config.position === 'r') {
                config.position = 'right';
            }else if (config.position === 'b') {
                config.position = 'bottom';
            }else if (config.position === 'l') {
                config.position = 'left';
            }else if(config.position === 'm') {
                config.position = 'middle';
            }
        }

        // 类型
        if (config.type) {
            config.type = parseInt(config.type);
            if(config.type === 1) {
                config.type = 'black';
            }else if(config.type === 2) {
                config.type = 'white';
            }else if (config.type === 'r') {
                config.type = 'ready';
            }else if (config.type === 'n') {
                config.type = 'noready';
            }else if (config.type === 'u') {
                config.type = 'url';
            }else if (config.type === 'h') {
                config.type = 'html';
            }else if(config.type === 'p') {
                config.type = 'photo';
            }else if(config.type === 'a') {
                config.type = 'alert';
            }else if(config.type === 'c') {
                config.type = 'confirm';
            }
        }

        // 图标
        config.icon_color = '';
        if (config.icon) {
            if (typeof(config.icon) === 'object') {
                config.icon_color = config.icon[1];
                config.icon = config.icon[0];
            }
            config.icon = parseInt(config.icon);
            config.icon_flag = true;
            if (config.icon === 1) {
                config.icon = 'success';
            }else if (config.icon === 2) {
                config.icon = 'error';
            }else if (config.icon === 3) {
                config.icon = 'warning';
            }else if (config.icon === 4) {
                config.icon = 'ask';
            }else if (config.icon === 5) {
                config.icon = 'hello';
            }
            if (config.icon !== 'success' &&
                config.icon !== 'error' &&
                config.icon !== 'warning' &&
                config.icon !== 'ask' &&
                config.icon !== 'hello') {
                config.icon_flag = false;
            }
        }

        // 文字对齐
        if (config.align) {
            config.align = config.align.toLowerCase();
            if (config.align === 'l') {
                config.align = 'left';
            }else if (config.align === 'c') {
                config.align = 'center';
            }else if (config.align = 'r') {
                config.align = 'right';
            }
        }
        return config;
    };

    // 入口
    Layer.parent.creat = function () {
        var that = this,
            config = that.config;

        // 1. 构建内部html
        var html = that.html();
        if(!html){
            return false;
        }

        // 2. 创建元素 设置id 将layer追加到body中
        var main_elem = createElem('div');
        main_elem.setAttribute('id', that.mainid);
        main_elem.classList.add('layer-main');
        main_elem.innerHTML = html;
        var layer_main = document.getElementById(that.mainid);
        that.layer_main = layer_main;

        // 3. add classname, attr
        that.attr();

        // 4. 添加动画效果
        that.on();

        // 5. 后续处理
        that.after();
    }

    // 1. create html
    Layer.parent.html = function () {
        var that = this,
            config = that.config,
            html = '';

        // 短消息
        if (config.model === 'msg') {
            html += '<p>';

            if (config.icon) {
                var i_html = '';
                if (config.icon === 'success') {
                    i_html = '<i class="layer-iconfont layer-icon-'+ config.icon +'">&#xe605;</i>';
                } else if (config.icon === 'error') {
                    i_html = '<i class="layer-iconfont layer-icon-'+ config.icon +'">&#xe600;</i>';
                }
                html += config.icon_flag === true ? i_html : '';
            }

            html += config.msg + '</p>';
        }

        return html;
    }

    // 3. add classname, attr
    Layer.parent.attr = function () {
        var that = this,
            config = that.config,
            layer_main = that.layer_main;

        var layerMainCenter = function (elem) {
            var layer_main = elem.offsetWidth;
            setStyle(elem, {
                'margin-left': (-parseInt(layer_main) / 2) + 'px',
            });
        }

        // 短消息
        if (config.model === 'msg') {
            layer_main.classList.add('layer-msg');
            layer_main.classList.add('layer-msg-' + config.position);
            layer_main.classList.add('layer-msg-' + config.type);
            setStyle(layer_main, {'white-space': 'nowrap',});

            layerMainCenter(layer_main);

            setStyle(layer_main, {'white-space': '',});
        }

        if (config.zindex) {
            setStyle(layer_main, {'z-index': config.zindex});
        }
    }

    // 4. 添加动画
    Layer.parent.on = function () {
        var that = this,
            config = that.config,
            layer_main = that.layer_main;

        setTimeout(function(){
            layer_main.classList.add('xon');
        }, 1);
    }

    // 5. 后续处理
    Layer.parent.after = function () {
        var that = this,
            config = that.config,
            layer_main = that.layer_main;

        //短消息、气泡层
        if(config.model === 'msg') {
            // 自动关闭
            that.autoClose();
        }
    }

    // 自动关闭
    Layer.parent.autoClose = function () {
        var that = this,
            config = that.config,
            layer_main = that.layer_main;

        // 倒计时
        if (layer_main.getElementsByClassName('layer_times')[0]) {}else{
            var time = config.time;
            if(time && time !== 0){
                setTimeout(function(){
                    that.close();
                }, time * 1000);
            }
        }
    }

    // close
    Layer.parent.close = function (close_id) {
        var that = this,
            config = that.config,
            check_lock = false;

        if (close_id) {}else{
            var layer_main = that.layer_main;
            if(config.lock === true){
                checkLock = true;
            }
        }

        if(!layer_main){
            return false;
        }

        // 移除元素
        layer_main.classList.remove('xon');
        setTimeout(function(){
            var parent_layer_main = layer_main.parentNode;
            if(parent_layer_main){
                parent_layer_main.removeChild(layer_main);
            }
            that.callback && that.callback();
        }, 201);
    }

    Layer.parent.xcstrRep = function(str){
        str = str.replace(/[\s\n\r]/g,''); //空格换行回车
        str = encodeURIComponent(str).toLowerCase();

        var reparr = [
            [/true/g,'1'],
            [/false/g,'0'],
            [/%/g,''],
            [/\(/g,''],
            [/\)/g,''],
            [/open/g,'o'],
            [/ready/g,'r'],
            [/noready/g,'n'],
            [/url/g,'u'],
            [/html/g,'h'],
            [/photo/g,'p'],
            [/function/g,'f'],
            [/99999/g,'9']
        ];
        for(var i=0; i<reparr.length; i++){
            str = str.replace(reparr[i][0], reparr[i][1]);
        }

        return str;
    };

    // 将 layer 绑定到 window
    window.layer = {
        version: '1.0.0',

        msg: function(msg, config = {}, callback = null) {
            var options = {
                model: 'msg',
                msg: msg,
                time: config.time ? config.time : 2,
                type: config.type ? config.type : 1,
                position: config.position ? config.position : 'middle',
                icon: config.icon ? config.icon : 0,
                zindex: config.zindex ? config.zindex : 99999,
            };
            if (callback) {
                options['callback'] = callback;
            }
            return(this.run(options));
        },

        //核心方法
        run: function(options){
            var x = new Layer(options);
            return x.mainid;
        },
    };
}(window, '/static/js/lib/layer/css/layer.css'));
